﻿using System;
using System.Threading.Tasks;
using System.Windows;

namespace WpfExample01.View.TextBox
{
    /// <summary>
    /// TextBoxExample01.xaml 的交互逻辑
    /// </summary>
    public partial class TextBoxExample01 : Window
    {
        readonly Window parentWindow = null;
        public TextBoxExample01(Window parentWindow)
        {
            InitializeComponent();
            this.Show();

            this.parentWindow = parentWindow;
            parentWindow.Hide();
        }

        public void ReturnToParentWindow(object sender, RoutedEventArgs e)
        {
            parentWindow.Show();
            this.Close();
        }

        private async void StartButton_Click(object sender, RoutedEventArgs e)
        {
            for (int i = 0; i < 50; i++)
            {
                // 模拟任务执行的时间，使用Task.Delay代替Thread.Sleep
                await Task.Delay(200);
                string message = $"时间:{DateTime.Now} - 日志:{i}";
                AppendLog(message);
            }
        }

        private void StopButton_Click(object sender, RoutedEventArgs e)
        {
            logTextBox.Clear();
        }

        // 向日志控制台添加日志
        public void AppendLog(string message)
        {
            // 使用Dispatcher确保线程安全
            Dispatcher.Invoke(() =>
            {
                logTextBox.AppendText(message + Environment.NewLine);
                // 自动滚动到最新的日志
                logTextBox.ScrollToEnd();
            });
        }
    }
}
